﻿using MiniFox.Configurations;
using MiniFox.Tasks.Configurations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MiniFox.Tasks.Providers
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class TaskItemProvider
    {
        /// <summary>
        /// 
        /// </summary>
        protected TaskItemProvider()
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public abstract TaskItem[] LoadTaskItems();
    }

    internal class DefaultTaskItemProvider : TaskItemProvider
    {
        internal DefaultTaskItemProvider()
        {

        }

        public override TaskItem[] LoadTaskItems()
        {
            List<TaskItem> list = new List<TaskItem>();
            var taskItemConfigs = ConfigurationFactory.GetConfig<TaskItemConfigCollection>();
            foreach (TaskItemConfig itemConfig in taskItemConfigs)
            {
                TaskItem taskItem;

                List<TaskAction> actions = new List<TaskAction>();
                foreach(var providerSetting in itemConfig.TaskActions)
                {
                    Type type = providerSetting;
                    if (type == null)
                        continue;

                    var action = Activator.CreateInstance(type, providerSetting.Name) as TaskAction;
                    if (action != null)
                        actions.Add(action);
                }
                var taskScheduler = new TaskScheduler
                {
                    Duration = itemConfig.Duration,
                    DurationUnit = itemConfig.DurationUnit,
                    ScheduleType = itemConfig.ScheduleType,
                    StartTime = itemConfig.StartTime,
                    EndTime = itemConfig.EndTime,
                    StopOnError = itemConfig.StopOnError
                };
                if (itemConfig.TaskItemType == null)
                {
                    taskItem = new TaskItem(itemConfig.Name, taskScheduler, actions.ToArray());
                }
                else
                {
                    taskItem = Activator.CreateInstance(itemConfig.TaskItemType, itemConfig.Name, taskScheduler, actions.ToArray()) as TaskItem;
                }
                list.Add(taskItem);
            }
            return list.ToArray();
        }
    }
}
